<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/12/18
 * Time: 16:56
 */

namespace app\utils;


class TimeUtil
{
    /**
     * 返回当前的毫秒数
     * @return float
     */
    public static function msecTime()
    {
        list($msecTime, $secTime) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msecTime) + floatval($secTime)) * 1000);
    }

    /**
     * 获取当前日期
     *
     * @param int $flag 0-精确到秒，1-精确到天
     * @return false|string
     */
    public static function getCurrentDate(int $flag = 0)
    {
        switch ($flag) {
            case 0:
                return date('Y-m-d H:i:s');
                break;
            case 1:
                return date('Y-m-d');
                break;
        }
    }

    /**
     *获取当前月份第一天和最后一天
     * @param $datetime | 时间格式datetime
     * @return array
     */
    public static function getMonthFirstAndLastDay($datetime)
    {

        $firstDay = date('Y-m-01', strtotime($datetime));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        return [
            'first' => $firstDay . ' 00:00:00',
            'last' => $lastDay . ' 23:59:59'
        ];
    }

    public static function mdate($time = NULL)
    {
        $text = '';
        $time = $time === NULL || $time > time() ? time() : intval($time);
        $t = time() - $time; //时间差 （秒）
        $y = date('Y', $time) - date('Y', time());//是否跨年
        switch ($t) {
            case $t == 0:
                $text = '刚刚';
                break;
            case $t < 60:
                $text = $t . '秒前'; // 一分钟内
                break;
            case $t < 60 * 60:
                $text = floor($t / 60) . '分钟前'; //一小时内
                break;
            case $t < 60 * 60 * 24:
                $text = floor($t / (60 * 60)) . '小时前'; // 一天内
                break;
            case $t < 60 * 60 * 24 * 3:
                $text = floor($time / (60 * 60 * 24)) == 1 ? '昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time); //昨天和前天
                break;
            case $t < 60 * 60 * 24 * 30:
                $text = date('m月d日 H:i', $time); //一个月内
                break;
            case $t < 60 * 60 * 24 * 365 && $y == 0:
                $text = date('m月d日', $time); //一年内
                break;
            default:
                $text = date('Y年m月d日', $time); //一年以前
                break;
        }

        return $text;
    }
}